# coding: utf-8
from typing import Literal, List

from PySide6.QtCore import QSize, Signal
from PySide6.QtGui import QResizeEvent, QColor
from PySide6.QtWidgets import QApplication
from loguru import logger
from qfluentwidgets import SplashScreen, FluentIcon as FI, NavigationItemPosition, InfoBar, isDarkTheme, MessageBox

from .bookShelf_interface import BookShelfInterface
from .home_interface import HomeInterface
from .plugin_interface import PluginInterface
from .search_interface import SearchInterface
from .setting_interface import SettingInterface
from .top_interfaces import InfoInterface, PhotosInterface, WebEngineView
from ..common import SingleIcon, signalBus, APIBase, pluginManager, init_create_table, cfg, BookInfoModel, BookItemModel
from ..components import FluentWindow, queue_thread_manager, ImageLabel


class MainWindow(FluentWindow):
    closed = Signal()

    def __init__(self):
        super().__init__()
        self.backgroundImage = ImageLabel(self)
        self.initWindow()
        # 顶部页面
        self.infoInterface = InfoInterface(self)
        self.photosInterface = PhotosInterface(self)
        self.webView = WebEngineView(self)

        # 子页面
        self.homeInterface = HomeInterface(self)
        self.searchInterface = SearchInterface(self)
        self.bookShelfInterface = BookShelfInterface(self)
        self.pluginInterface = PluginInterface(self)
        self.settingInterface = SettingInterface(self)

        self.initSubInterfaces()
        self.connectSignals()

    def initWindow(self):
        self.setMinimumSize(1000, 600)
        self.setWindowIcon(SingleIcon.LOGO_PNG.icon())
        self.setWindowTitle('异次元')

        # 设置背景图片
        self.backgroundImage.setEnabledRandomColor(False)
        self.backgroundImage.setEnabledMask(True)
        self.backgroundImage.setScaledContents(True)
        self.backgroundImage.setGeometry(0, 0, self.width(), self.height())
        self.backgroundImage.lower()
        # 创建启动画面
        self.splashScreen = SplashScreen(self.windowIcon(), self)
        self.splashScreen.setIconSize(QSize(106, 106))
        self.splashScreen.raise_()

        desktop = QApplication.primaryScreen().availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w // 2 - self.width() // 2, h // 2 - self.height() // 2)
        self.show()
        init_create_table()
        pluginManager.loadAll()

        QApplication.processEvents()
        self.splashScreen.finish()
        self.titleBar.raise_()

    def initSubInterfaces(self):
        isTransparent = True
        self.addSubInterface(self.homeInterface, FI.HOME, "首页", isTransparent=isTransparent)
        self.addSubInterface(self.searchInterface, FI.SEARCH, "搜索", isTransparent=isTransparent)

        pos = NavigationItemPosition.BOTTOM
        self.navigationInterface.addSeparator(pos)
        self.addSubInterface(self.bookShelfInterface, FI.BOOK_SHELF, "书架", pos, isTransparent=isTransparent)
        self.addSubInterface(self.pluginInterface, FI.APPLICATION, "插件", pos, isTransparent=isTransparent)
        self.addSubInterface(self.settingInterface, FI.SETTING, "设置", pos, isTransparent=isTransparent)

        # 添加顶部页面
        self.addTotalWidget(self.infoInterface)
        self.addTotalWidget(self.photosInterface)
        self.addTotalWidget(self.webView)

    def connectSignals(self):
        self.infoInterface.closed.connect(self.onTotalClosed)
        self.photosInterface.closed.connect(self.onTotalClosed)
        self.webView.closed.connect(self.onTotalClosed)

        signalBus.msgSignal.connect(self.showMsgBox)
        signalBus.sysMsgSignal.connect(self.showSysMsgBox)
        signalBus.infoSignal.connect(self.loadInfo)
        signalBus.photoSignal.connect(self.loadPhotos)
        signalBus.threadStartSignal.connect(self.splashScreen.show)
        signalBus.threadFinishSignal.connect(self.splashScreen.finish)
        signalBus.webUrlSignal.connect(self.loadWeb)
        # 壁纸信号
        self.backgroundImage.setBlurEffect(cfg.get(cfg.wallpaperBlurRadius))
        self.backgroundImage.setImage(cfg.get(cfg.wallpaperPath))
        self.backgroundImage.setVisible(cfg.get(cfg.wallpaperEnabled))
        self.backgroundImage.setMaskOpacity(cfg.get(cfg.wallpaperOpacity))
        self.backgroundImage.setMaskLightColor(cfg.get(cfg.wallpaperLightMaskColor))
        self.backgroundImage.setMaskDarkColor(cfg.get(cfg.wallpaperDarkMaskColor))
        signalBus.wallpaperEnabledChanged.connect(self.backgroundImage.setVisible)
        signalBus.wallpaperChanged.connect(self.backgroundImage.setImage)
        signalBus.wallpaperOpacityChanged.connect(self.backgroundImage.setMaskOpacity)
        signalBus.wallpaperLightColorChanged.connect(self.backgroundImage.setMaskLightColor)
        signalBus.wallpaperDarkColorChanged.connect(self.backgroundImage.setMaskDarkColor)
        signalBus.wallpaperBlurRadiusChanged.connect(self.backgroundImage.setBlurEffect)

    def showMsgBox(self, level: Literal['info', 'success', 'warning', 'error'], msg: str):
        if level == 'info':
            InfoBar.info('提示', msg, duration=2000, parent=self.window())
        elif level == 'success':
            InfoBar.success('成功', msg, duration=2000, parent=self.window())
        elif level == 'warning':
            InfoBar.warning('警告', msg, duration=2000, parent=self.window())
        elif level == 'error':
            InfoBar.error('错误', msg, duration=3000, parent=self.window())

    def showSysMsgBox(self, msg: str):
        dialog = MessageBox('未处理的错误', msg, self)
        dialog.setContentCopyable(True)
        dialog.cancelButton.hide()
        dialog.exec()

    def onTotalClosed(self):
        widget = self.totalStackedWidget.currentWidget()
        if widget == self.infoInterface:
            logger.debug(f'关闭{widget.objectName()}, 切换到导航页面')
            self.totalStackedWidget.setCurrentWidget(self.navigationWidget)
        elif widget in [self.photosInterface, self.webView]:
            logger.debug(f'关闭{widget.objectName()}, 切换到信息页面')
            self.totalStackedWidget.setCurrentWidget(self.infoInterface)

    def loadInfo(self, obj: APIBase, url: str):
        logger.debug(f'加载信息{obj.name} {url}')
        self.infoInterface.clear()
        self.infoInterface.loadInfo(obj, url)
        self.setTotalCurrentWidget(self.infoInterface)

    def loadPhotos(self, model: BookItemModel, models: List[BookItemModel]):
        obj: APIBase = model.source
        url = model.photo_url
        logger.debug(f'加载图片{obj.name} {url}')
        self.photosInterface.clear()
        self.photosInterface.loadPhoto(obj, url, models)
        self.setTotalCurrentWidget(self.photosInterface)

    def loadWeb(self, url: str):
        logger.debug(f'加载网页 {url}')
        self.webView.load(url)
        self.setTotalCurrentWidget(self.webView)

    def closeEvent(self, event, /):
        queue_thread_manager.close()
        super().closeEvent(event)

    def resizeEvent(self, event: QResizeEvent):
        self.backgroundImage.setGeometry(0, 0, self.width(), self.height())
        super().resizeEvent(event)
